package cn.hubujyjs.lp.service.impl;

import cn.hubujyjs.lp.exception.LpException;
import cn.hubujyjs.lp.service.OssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OssServiceImpl implements OssService {
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    @Value("${spring.cloud.alicloud.access-key}")
    String accessId ;

    @Value("${spring.cloud.alicloud.secret-key}")
    String accessKey ;

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint ;

    // 填写Bucket名称，例如examplebucket。
    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket ;
    @Override
    public String uploadPicture(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(date);
        String originalFilename = file.getOriginalFilename();
        String suffix;
        try {
            int i = originalFilename.lastIndexOf('.');
            suffix = originalFilename.substring(i);
        } catch (Exception e) {
            throw new LpException("上传的文件格式不正确");
        }
        String key ="lp/" +now + suffix;
        try {
            ossClient.putObject(bucket, key,file.getInputStream());
        } catch (IOException e) {
            throw new LpException("文件写入错误");
        }
        String url ="https://hjtblogpic.oss-cn-shanghai.aliyuncs.com/"+key;
        return url;
    }
}
